package test.n00100;


import java.util.Arrays;

public class Problem00140 {
    public static void main(String[] args) {
        println(new String[]{"flower", "flow", "flight"});
        println(new String[]{"dog", "racecar", "car"});
        println(new String[]{"reflower", "flow", "flight"});
    }

    public static void println(String[] strs) {
        Solution ss = new Solution();
        System.out.println(Arrays.asList(strs) + "," + ss.longestCommonPrefix(strs));
    }

    public static class Solution {

        /**
         * 编写一个函数来查找字符串数组中的最长公共前缀。
         * <p>
         * 如果不存在公共前缀，返回空字符串 ""。
         * <p>
         * 提示：
         * <p>
         * 1 <= strs.length <= 200
         * 0 <= strs[i].length <= 200
         * strs[i] 仅由小写英文字母组成
         * <p>
         * 解题思路:
         * 横向扫描
         * 依次对比两个字符串是否前缀相等
         *
         * @param strs
         * @return
         */
        public String longestCommonPrefix(String[] strs) {
            String prefix = strs[0];
            final int length = strs.length;
            for (int i = 1; i < length; i++) {
                prefix = longestCommonPrefix(prefix, strs[i]);
                if (prefix.equals("")) {
                    break;
                }
            }
            return prefix;
        }

        public String longestCommonPrefix(String str1, String str2) {
            int minLen = Math.min(str1.length(), str2.length());

            int index = 0;
            while (index < minLen && str1.charAt(index) == str2.charAt(index)) {
                index++;
            }
            return str1.substring(0, index);
        }
    }
}
